﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using System.Linq;
using SIMSProject.Helpers.QuickLaunch;

namespace SIMSProject.WebParts
{
    public class QuickLaunchManagerWebPart : WebPart
    {
        public override PartChromeType ChromeType
        {
            get { return PartChromeType.None; }
            set { base.ChromeType = value; }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            CreateChildControlsForPageTitle();
            CreateChildControlsForPageDescription();
            CreateChildControlsForPageTitleInTitleArea();
        }

        private void CreateChildControlsForPageDescription()
        {
            var control = Page.Master.FindControl("PlaceHolderPageDescription");
            if (control != null)
            {
                control.Controls.Add(new LiteralControl(HttpContext.GetGlobalResourceObject("wss", "quiklnch_description").ToString()));
            }
        }

        private void CreateChildControlsForPageTitle()
        {
            var control = Page.Master.FindControl("PlaceHolderPageTitle");
            if (control != null)
            {
                control.Controls.Add(new LiteralControl(HttpContext.GetGlobalResourceObject("wss", "quiklnch_pagetitle").ToString()));
            }
        }

        private void CreateChildControlsForPageTitleInTitleArea()
        {
            var web = SPContext.Current.Web;
            var control = Page.Master.FindControl("PlaceHolderPageTitleInTitleArea");
            if (control != null)
            {
                var lnkSettings = new HyperLink
                                      {
                                          NavigateUrl = string.Format("{0}/_layouts/settings.aspx", web.Url),
                                          Text = HttpContext.GetGlobalResourceObject("wss", "settings_pagetitle").ToString()
                                      };
                control.Controls.Add(lnkSettings);
                control.Controls.Add(new LiteralControl("&#32;"));
                control.Controls.Add(new ClusteredDirectionalSeparatorArrow());
                control.Controls.Add(new LiteralControl("&#32;"));
                control.Controls.Add(new EncodedLiteral { Text = HttpContext.GetGlobalResourceObject("wss", "quiklnch_pagetitle").ToString() });
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (SPContext.Current.Web.CurrentUser == null)
            {
                SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
            }

            if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.AddAndCustomizePages))
            {
                SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
            }

            var ribbon = SPRibbon.GetCurrent(Page);
            if (ribbon != null)
            {
                 ribbon.TrimById("Ribbon.Read");
                 ribbon.TrimById("Ribbon.WebPartPage");
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-v4propertysheetspacing");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            RenderToolBar(writer);
            writer.RenderEndTag(); // td
            writer.RenderEndTag(); // tr

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.AddAttribute(HtmlTextWriterAttribute.Rowspan, "1");
            writer.AddAttribute(HtmlTextWriterAttribute.Height, "5");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<img src=\"/_layouts/images/blank.gif\" width=\"1\" height=\"1\" alt=\"\" />");
            writer.RenderEndTag(); // td
            writer.RenderEndTag(); // tr

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-descriptiontext ms-naveditor");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            RenderQuickLaunch(writer);
            writer.RenderEndTag(); // td

            writer.RenderEndTag(); // tr

            writer.RenderEndTag(); // table
        }

        private void RenderQuickLaunch(HtmlTextWriter writer)
        {
            var items = QuickLaunchManager.GetAllQuickLaunchItems(SPContext.Current.Web).OrderBy(item => item.Position);
            var parents = items.Where(item => item.ParentId == 0).OrderBy(item => item.Position);

            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            var rawUrl = SPEncode.UrlEncode(Page.Request.RawUrl);
            foreach (var parent in parents)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-gb");
                writer.AddAttribute(HtmlTextWriterAttribute.Width, "20px");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("QuickLaunchItem.aspx?Id={0}&ParentId=1025&Source={1}", parent.Id, rawUrl));
                writer.RenderBeginTag(HtmlTextWriterTag.A);

                writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
                writer.AddAttribute(HtmlTextWriterAttribute.Src, "/_layouts/images/edititem.gif");
                writer.RenderBeginTag(HtmlTextWriterTag.Img);
                writer.RenderEndTag(); // img

                writer.RenderEndTag(); // a

                writer.RenderEndTag(); // td

                writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-gb");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.RenderBeginTag(HtmlTextWriterTag.B);

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-standardheader");
                writer.RenderBeginTag(HtmlTextWriterTag.H3);
                writer.Write(parent.Title);
                writer.RenderEndTag(); // h3
                writer.RenderEndTag(); // b

                writer.RenderEndTag(); // td

                writer.RenderEndTag(); // tr

                var parentId = parent.Id;
                var childs = items.Where(item => item.ParentId == parentId).OrderBy(item => item.Position);
                foreach (var child in childs)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-vb2");
                    writer.AddAttribute(HtmlTextWriterAttribute.Width, "20px");
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write("<img src=\"/_layouts/images/blank.gif\" width=\"20\" height=\"1\" alt=\"\" />");
                    writer.RenderEndTag(); // td

                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-vb2");
                    writer.AddAttribute(HtmlTextWriterAttribute.Width, "20px");
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);

                    writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("QuickLaunchItem.aspx?Id={0}&Source={1}", child.Id, rawUrl));
                    writer.RenderBeginTag(HtmlTextWriterTag.A);

                    writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
                    writer.AddAttribute(HtmlTextWriterAttribute.Src, "/_layouts/images/edititem.gif");
                    writer.RenderBeginTag(HtmlTextWriterTag.Img);
                    writer.RenderEndTag(); // img

                    writer.RenderEndTag(); // a

                    writer.RenderEndTag(); // td

                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-vb2");
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(child.Title);
                    writer.RenderEndTag(); // td

                    writer.RenderEndTag(); // tr
                }
            }

            writer.RenderEndTag(); // table
        }

        private void RenderToolBar(HtmlTextWriter writer)
        {
            var rawUrl = SPEncode.UrlEncode(Page.Request.RawUrl);

            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "2");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Nowrap, "nowrap");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            RenderToolBarButton(writer, HttpContext.GetGlobalResourceObject("wss", "topnav_newlink").ToString(), string.Format("QuickLaunchItem.aspx?Source={0}", rawUrl), "/_layouts/images/newitem.gif");
            writer.RenderEndTag(); // td

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-separator");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("/");
            writer.RenderEndTag(); // td

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Nowrap, "nowrap");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            RenderToolBarButton(writer, HttpContext.GetGlobalResourceObject("wss", "quiklnch_newcat").ToString(), string.Format("QuickLaunchItem.aspx?ParentId=1025&Source={0}", rawUrl), "/_layouts/images/newitem.gif");
            writer.RenderEndTag(); // td

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-separator");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("/");
            writer.RenderEndTag(); // td

            //writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            //writer.AddAttribute(HtmlTextWriterAttribute.Nowrap, "nowrap");
            //writer.RenderBeginTag(HtmlTextWriterTag.Td);
            //RenderToolBarButton(writer, HttpContext.GetGlobalResourceObject("wss", "topnav_changeorder").ToString(), "", "/_layouts/images/reorder.gif");
            //writer.RenderEndTag(); // td

            writer.AddAttribute(HtmlTextWriterAttribute.Width, "99%");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Nowrap, "nowrap");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("<img width=\"1\" height=\"18\" alt=\"\" src=\"/_layouts/images/blank.gif\" complete=\"complete\"/>");
            writer.RenderEndTag();

            writer.RenderEndTag(); // tr

            writer.RenderEndTag(); // tbody

            writer.RenderEndTag(); // table
        }

        private static void RenderToolBarButton(HtmlTextWriter writer, string text, string  url, string iconUrl)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "1");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            // Td #1
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Nowrap, "nowrap");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            writer.AddAttribute(HtmlTextWriterAttribute.Title, text);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Href, url);
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            
            writer.AddAttribute(HtmlTextWriterAttribute.Style, "border-right-width: 0px; width: 16px; border-top-width: 0px; border-bottom-width: 0px; height: 16px; border-left-width: 0px;");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, iconUrl);
            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            writer.RenderEndTag(); // img

            writer.RenderEndTag(); // a

            writer.RenderEndTag(); // td

            // Td #2
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Nowrap, "nowrap");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            writer.AddAttribute(HtmlTextWriterAttribute.Title, text);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-toolbar");
            writer.AddAttribute(HtmlTextWriterAttribute.Href, url);
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write(text);
            writer.RenderEndTag(); // a

            writer.RenderEndTag(); // td

            writer.RenderEndTag(); // tr

            writer.RenderEndTag(); // tbody

            writer.RenderEndTag(); // table
        }
    }
}